#!/usr/bin/env python3
"""
MySQL数据库连接工具
"""

import sys
from sql_pools.mysql_config import MySQLClient


class DBQuery:
    """数据库查询工具类"""
    
    def __init__(self, host='10.141.194.72', port=23306, user='viu_root', password='myviu_4359', database='d_cgboss_info'):
        """初始化数据库连接参数"""
        self.host = host
        self.port = port
        self.user = user
        self.password = password
        self.database = database
        self._client = None
    
    def connect(self):
        """连接数据库"""
        try:
            # 创建MySQL客户端实例
            self._client = MySQLClient(
                host=self.host,
                port=self.port,
                user=self.user,
                password=self.password,
                database=self.database
            )
            print(f"连接到 {self.host}:{self.port}/{self.database} 成功!")
            return True
        except Exception as e:
            print(f"数据库连接失败: {str(e)}")
            return False
    
    def query(self, sql, params=None, print_result=True):
        """
        执行SQL查询
        
        Args:
            sql: SQL查询语句
            params: 查询参数
            print_result: 是否打印结果
            
        Returns:
            查询结果列表
        """
        # 如果客户端未初始化，先连接
        if not self._client:
            if not self.connect():
                return None
        
        try:
            print(f"执行查询: {sql}")
            results = self._client.execute_query(sql, params)
            
            if print_result:
                self._print_results(results)
            
            return results
        except Exception as e:
            print(f"查询执行失败: {str(e)}")
            return None



# 使用示例
if __name__ == "__main__":
    # 创建查询对象
    db = DBQuery()
    
    # 执行VM查询
    vm_query = "SELECT * FROM iaas_vm WHERE vm_id IN (3482)"
    vm_data = db.query(vm_query)
    
